﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Yz.Base;
using Yz.Core.Extensions; 
using Yz.Model.Config;
using Yz.Mvc.Middlewares;

namespace Yz.FileService.Middlewares
{
    public class BaseUploadMiddleware: BaseMiddleware
    {

        /// <summary>
        /// 分片临时根目录
        /// </summary>
        protected readonly string tempFolder = "YzChunkTempFiles";
        protected readonly string yzTmpFile = "YzTmpFile";
        public IOptions<UploadConfig> _optionUploadConfig { get; set; }
        public IOptions<AppConfig> _optionAppConfig { get; set; }
        protected UploadConfig _uploadConfig => _optionUploadConfig.Value;
        protected AppConfig _appConfig => _optionAppConfig.Value;
        /// <summary>
        /// 验证接口认证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected async Task ValidateTokenAsync(HttpContext context)
        {
            string msg = "";
            context.Request.Headers.TryGetValue("appId", out StringValues appId);
            context.Request.Headers.TryGetValue("token", out StringValues token);
            if (string.IsNullOrEmpty(appId) || string.IsNullOrEmpty(token))
            {
                msg = "授权信息不能为空！";
            }
            var appInfo = _appConfig.Apps.Where(p => p.AppId == appId).FirstOrDefault();
            if (appInfo == null)
            {
                msg = "授权信息无效！";
            }
            int time = _appConfig.Time;
            string token1 = (appInfo.AppSecret + DateTime.Now.AddMinutes(-time).ToString(DateFormat.yMdH)).ToMd5Hash();
            string token2 = (appInfo.AppSecret + DateTime.Now.ToString(DateFormat.yMdH)).ToMd5Hash();
            string token3 = (appInfo.AppSecret + DateTime.Now.AddMinutes(time).ToString(DateFormat.yMdH)).ToMd5Hash();
            if (token != token1 && token != token2 && token != token3)
            {
                msg = "授权信息无效！";
            }
            if (!string.IsNullOrEmpty(msg))
            {
                await context.Response.WriteAsync(new VmUpFileBase()
                {
                    msg = msg
                }.ToJson());
                return;
            }
        }

        /// <summary>
        /// 为http添加header
        /// </summary>
        /// <param name="context"></param>
        protected void AddHttpOptionHeader(HttpContext context)
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
            context.Response.Headers.Add("Access-Control-Request-Method", "post");
            context.Response.Headers.Add("Access-Control-Allow-Headers", "content-type,jwt,origin,appId,token");
            context.Response.StatusCode = (int)HttpStatusCode.OK;
        }

        /// <summary>
        /// 返回不支持的http方式的提示
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        protected async Task AddHttpNotAllowedAsync(HttpContext context)
        {
            context.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; 
            await context.Response.WriteAsync(new VmUpFileBase()
            {
                msg = $"不支持此 '{context.Request.Method}' http 方法"
            }.ToJson());

        }
    }
}
